// 这份代码专门处理逻辑层的操作
const userDao = require('../dao/userDao');
const { createUserJwtToken, verifyJwtToken } = require('../util/server_jwt');
const powerService = require('./powerService');

const userService = {
    /*
     * 用户使用账号密码登录的方法
     */
    // async loginByAccountName(accountName, password) {
    //     // 密码加密（暂不实现，上线之后再实现）
    //     password = password;
    //     // 验证登录
    //     let result;
    //     try {
    //         let tmp = await userDao.loginByAccountName(accountName, password);
    //         if (tmp.length > 0) {
    //             // 生成jwt令牌
    //             let payload = {uid: tmp[0].uid, username: tmp[0].username};
    //             let jwt = await createUserJwtToken(payload, {expiresIn: '168h'});
    //             // 返回数据
    //             result = {success: true, msg: "登录成功", jwt: jwt};
    //         } else {
    //             result = {success: false, msg: "账号或密码错误", jwt: ""};
    //         }
    //     } catch (err) {
    //         result = {success: false, msg: "查询数据库时异常，登录失败", jwt: ""};
    //     }
    //     return result;
    // },

    /*
     * 用户使用账号密码登录的方法
     */
    // async loginByPhone(phone, password) {
    //     // 密码加密（暂不实现，上线之后再实现）
    //     password = password;
    //     // 验证登录
    //     let result;
    //     try {
    //         let tmp = await userDao.loginByPhone(phone, password);
    //         if (tmp.length > 0) {
    //             if (tmp[0].allowLogin == 'true') {
    //                 // 生成jwt令牌
    //                 let payload = {uid: tmp[0].uid, username: tmp[0].username, userType: tmp[0].userType};
    //                 let jwt = await createUserJwtToken(payload, {expiresIn: '168h'});
    //                 // 返回数据
    //                 result = {success: true, msg: "登录成功", jwt: jwt, userType: tmp[0].userType};
    //             } else {
    //                 result = {success: false, msg: "该账号已被冻结，请联系管理员", jwt: ""};
    //             }
    //         } else {
    //             result = {success: false, msg: "账号或密码错误", jwt: ""};
    //         }
    //     } catch (err) {
    //         result = {success: false, msg: "查询数据库时异常，登录失败", jwt: ""};
    //     }
    //     return result;
    // },
    
    /*
     * 用户使用工号密码登录的方法
     */
    async loginByWorkId(workId, password) {
        // 密码加密（暂不实现，上线之后再实现）
        password = password;
        // 验证登录
        let result;
        try {
            let tmp = await userDao.loginByWorkId(workId, password);
            if (tmp.length > 0) {
                if (tmp[0].allowLogin == 'true') {
                    // 生成jwt令牌
                    let payload = {uid: tmp[0].uid, username: tmp[0].username, userType: tmp[0].userType};
                    let jwt = await createUserJwtToken(payload, {expiresIn: '20h'});     // 将 jwt令牌 的有效时间设置为 20小时
                    // let jwt = await createUserJwtToken(payload, {expiresIn: '168h'});
                    // 返回数据
                    result = {success: true, msg: "登录成功", jwt: jwt, userType: tmp[0].userType};
                } else {
                    result = {success: false, msg: "该账号已被冻结，请联系管理员", jwt: ""};
                }
            } else {
                result = {success: false, msg: "工号或密码错误", jwt: ""};
            }
        } catch (err) {
            result = {success: false, msg: "查询数据库时异常，登录失败", jwt: ""};
        }
        return result;
    },

    /*
     * 用户使用jwt令牌验证登录的方法
     */
    async checkLoginByJWT(jwt) {
        let result;
        try {
            result = await verifyJwtToken(jwt);
        } catch (err) {
            result = {msg: "登录验证失败，请重新登录", login: false};
        }
        return result;
    },

    /*
     * 新增用户的方法
     */
    async addUser(jwt, userInfo) {
        // 用户身份认证
        let result = await userService.checkLoginByJWT(jwt);
        if (result.login == false) {
            return {success: false, msg: result.msg};
        }
        // 用户权限认证
        try {
            result = await powerService.checkPowerByUid(result.data.uid, '新增用户');
            if (result == false) {
                return {success: false, msg: "权限不足，无法操作"};
            }
        } catch (err) {
            return {success: false, msg: "操作过程中出错"};
        }
        // 执行具体操作
        try {
            result = await userDao.addUser(userInfo);
            if (result.affectedRows > 0) {
                result = {success: true, msg: "新增用户成功"};
            } else {
                result = {success: false, msg: "新增用户失败，插入过程中异常"};
            }
        } catch (err) {
            result = {success: false, msg: "新增用户失败，操作数据库异常"};
        }
        return result;
    },
    /*
     * 查询所有用户的方法
     */
    async getAllUserList(jwt) {
        // 用户身份认证
        result = await userService.checkLoginByJWT(jwt);
        if (result.login == false) {
            return {success: false, msg: result.msg};
        }
        let uid = result.data.uid;
        
        // 用户权限认证
        try {
            result = await powerService.checkPowerByUid(uid, '查看用户');
            if (result == false) {
                return {success: false, msg: "权限不足，无法操作"};
            }
        } catch (err) {
            return {success: false, msg: "操作过程中出错"};
        }

        try {
            result = await userDao.getAllUserList();
            result = { success: true, msg: "查询成功", allUserList: result };
        } catch (error) {
            result = { success: false, msg: "查看数据库时出错，查看失败" };
        }

        return result;
    },
    /*
     * 获取用户权限列表
     */
    async getUserPowerList(jwt) {
        // 用户身份认证
        let result = await userService.checkLoginByJWT(jwt);
        if (result.login == false) {
            return {success: false, msg: result.msg};
        }
        result = await powerService.getUserPowerList(result.data.uid);
        return result;
    },
    /*
     * 新增用户类型接口
     */
    async addUserType(jwt, addUserTypeInfo) {
        // 用户身份认证
        let result;
        result = await userService.checkLoginByJWT(jwt);
        if (result.login == false) {
            return {success: false, msg: result.msg};
        }
        let uid = result.data.uid;
        // 用户权限认证
        try {
            result = await powerService.checkPowerByUid(uid, '用户角色管理');
            if (result == false) {
                return {success: false, msg: "权限不足，无法操作"};
            }
        } catch (err) {
            return {success: false, msg: "操作过程中出错"};
        }
        try {
            result = await userDao.addUserType(addUserTypeInfo);
            result = { success: true, msg: result.msg, new_userTypeId: result.userTypeId };
        } catch (error) {
            result = { success: false, msg: "操作数据库时出错，查看失败" };
        }

        return result;
    },
    /*
     * 获取用户类型列表
     */
    async getAllUserTypeList(jwt) {
        // 用户身份认证
        let result;
        result = await userService.checkLoginByJWT(jwt);
        if (result.login == false) {
            return {success: false, msg: result.msg};
        }
        let uid = result.data.uid;
        // 用户权限认证
        try {
            result = await powerService.checkPowerByUid(uid, '用户角色管理');
            if (result == false) {
                return {success: false, msg: "权限不足，无法操作"};
            }
        } catch (err) {
            return {success: false, msg: "操作过程中出错"};
        }

        try {
            result = await userDao.getAllUserTypeList();
            result = { success: true, msg: "查询成功", allUserTypeList: result };
        } catch (error) {
            result = { success: false, msg: "查看数据库时出错，查看失败" };
        }

        return result;
    },
    /*
     * 获取所有辅导员列表
     */
    async getAllTeacherList(jwt) {
        // 用户身份认证
        let result;
        result = await userService.checkLoginByJWT(jwt);
        if (result.login == false) {
            return {success: false, msg: result.msg};
        }
        // 查询所有辅导员
        try {
            result = await userDao.getAllTeacherList();
            result = { success: true, msg: "查询成功", allTeacherList: result };
        } catch (error) {
            result = { success: false, msg: "查看数据库时出错，查看失败" };
        }
        return result;
    },
    /*
     * 修改用户信息以及类型
     */
    async changeUserInfoAndUserType(jwt, uid, username, accountName, phone, email, facultyId, password, userTypeId) {
        // 用户身份认证
        let result;
        result = await userService.checkLoginByJWT(jwt);
        if (result.login == false) {
            return {success: false, msg: result.msg};
        }
        let uid_usingByPower = result.data.uid;
        // 用户权限认证
        try {
            result = await powerService.checkPowerByUid(uid_usingByPower, '修改用户');
            if (result == false) {
                return {success: false, msg: "权限不足，无法操作"};
            }
        } catch (err) {
            return {success: false, msg: "操作过程中出错"};
        }
        // 修改用户处理
        try {
            let func = userDao.changeUserInfoAndUserType;
            if (password) {
                func = userDao.changeUserInfoAndUserTypeAndPassword;
            }
            result = await func(uid, username, accountName, phone, email, facultyId, userTypeId, password);
            result = { success: true, msg: "修改成功" };
        } catch (error) {
            result = { success: false, msg: "操作数据库时出错，修改失败" };
        }
        return result;
    },
    /*
     * 修改用户信息
     */
    async changeUserInfo(jwt, uid, username, accountName, phone, email, facultyId, password) {
        // 用户身份认证
        let result;
        result = await userService.checkLoginByJWT(jwt);
        if (result.login == false) {
            return {success: false, msg: result.msg};
        }
        let uid_usingByPower = result.data.uid;
        // 用户权限认证
        try {
            result = await powerService.checkPowerByUid(uid_usingByPower, '修改用户');
            if (result == false) {
                return {success: false, msg: "权限不足，无法操作"};
            }
        } catch (err) {
            return {success: false, msg: "操作过程中出错"};
        }
        // 修改用户处理
        try {
            let func = userDao.changeUserInfo;
            if (password) {
                func = userDao.changeUserInfoAndPassword;
            }
            result = await func(uid, username, accountName, phone, email, facultyId, password);
            result = { success: true, msg: "修改成功" };
        } catch (error) {
            result = { success: false, msg: "操作数据库时出错，修改失败" };
        }
        return result;
    },
    /*
     * 冻结用户
     */
    async updateUserAllowLogin(jwt, uid, allowLogin) {
        // 用户身份认证
        let result;
        result = await userService.checkLoginByJWT(jwt);
        if (result.login == false) {
            return {success: false, msg: result.msg};
        }
        let uid_usingByPower = result.data.uid;
        // 用户权限认证
        try {
            result = await powerService.checkPowerByUid(uid_usingByPower, '修改用户');
            if (result == false) {
                return {success: false, msg: "权限不足，无法操作"};
            }
        } catch (err) {
            return {success: false, msg: "操作过程中出错"};
        }
        // 真正的执行逻辑
        try {
            result = await userDao.updateUserAllowLogin(uid, allowLogin);
            result = { success: true, msg: "修改成功" };
        } catch (error) {
            result = { success: false, msg: "操作数据库时出错，修改失败" };
        }
        return result;
    },
    async getUserTypePowerList(jwt, userType) {
        // 用户身份认证
        let result;
        result = await userService.checkLoginByJWT(jwt);
        if (result.login == false) {
            return {success: false, msg: result.msg};
        }
        // 真正的执行逻辑
        try {
            result = await userDao.getUserTypePowerList(userType);
            result = { success: true, msg: "查询成功", result };
        } catch (error) {
            result = { success: false, msg: "查询数据库时出错，查询失败" };
        }
        return result;
    },
    async updateUserTypePowerList(jwt, userType, powerList) {
        // 用户身份认证
        let result;
        result = await userService.checkLoginByJWT(jwt);
        if (result.login == false) {
            return {success: false, msg: result.msg};
        }
        let uid_usingByPower = result.data.uid;
        // 用户权限认证
        try {
            result = await powerService.checkPowerByUid(uid_usingByPower, '用户角色管理');
            if (result == false) {
                return {success: false, msg: "权限不足，无法操作"};
            }
        } catch (err) {
            return {success: false, msg: "操作过程中出错"};
        }
        // 真正的执行逻辑
        try {
            result = await userDao.getUserTypeById(userType);
            if (result.length == 0) {
                return { success: false, msg: "用户角色不存在" };
            } else if (result[0].userTypeName == '系统管理员') {
                return { success: false, msg: "管理员角色无法修改权限" };
            } else {
                result = await userDao.updateUserTypePowerList(userType, powerList);
                if (result) {
                    result = { success: true, msg: "修改成功" };
                } else {
                    result = { success: false, msg: "修改失败" };
                }
            }
        } catch (error) {
            result = { success: false, msg: "修改数据库时出错，修改失败" };
        }
        return result;
    },
    async getUidAndWorkIdByUsername(jwt, username) {
        // 用户身份认证
        let result;
        result = await userService.checkLoginByJWT(jwt);
        if (result.login == false) {
            return {success: false, msg: result.msg};
        }
        let uid_usingByPower = result.data.uid;
        // 真正的执行逻辑
        try {
            result = await userDao.getUidAndWorkIdByUsername(username);
            if (result.length == 0) {
                return { success: false, msg: "用户不存在" };
            } else {
                return { success: true, msg: "获取成功", data: result[0] };
            }
        } catch (error) {
            result = { success: false, msg: "修改数据库时出错，修改失败" };
        }
        return result;
    }
};

module.exports = userService;